package com.qst.crop.controller;

import com.qst.crop.entity.Finance;
import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.service.FinanceService;
import com.qst.crop.service.BankService;
import com.qst.crop.entity.Bank;
import com.qst.crop.entity.Intention;
import com.qst.crop.model.Recommend;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.List;

/**
 * (Finance)表控制层
 *
 * @author Wlj
 * @since 2025-09-02 15:28:21
 */
@RestController
@RequestMapping("finance")
public class FinanceController {
    /**
     * 服务对象
     */
    @Resource
    private FinanceService financeService;

    @Resource
    private BankService bankService;

    /**
     * 分页查询
     *
     * @param finance 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Finance>> queryByPage(Finance finance, PageRequest pageRequest) {
        return ResponseEntity.ok(this.financeService.queryByPage(finance, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Finance> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.financeService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param finance 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Finance> add(Finance finance) {
        return ResponseEntity.ok(this.financeService.insert(finance));
    }

    // 新增：添加融资（JSON）
    @PostMapping("/add")
    public Result<Finance> addFinance(@RequestBody Finance finance) {
        Finance saved = financeService.insert(finance);
        return new Result<Finance>(true, StatusCode.OK, "添加成功", saved);
    }

    /**
     * 编辑数据
     *
     * @param finance 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Finance> edit(Finance finance) {
        return ResponseEntity.ok(this.financeService.update(finance));
    }

    // 新增：根据JSON修改融资
    @PutMapping("/update")
    public Result<Finance> updateFinance(@RequestBody Finance finance) {
        Finance updated = financeService.update(finance);
        return new Result<Finance>(true, StatusCode.OK, "修改成功", updated);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.financeService.deleteById(id));
    }

    // 新增：查询银行列表（供融资页面选择）
    @GetMapping("/selectbank")
    public Result<List<Bank>> selectBank() {
        List<Bank> banks = this.bankService.selectAll();
        return new Result<List<Bank>>(true, StatusCode.OK, "查询成功", banks);
    }

    // ===== 融资意向与推荐 =====
    @GetMapping("/intention/{name}")
    public Result<Intention> selectIntentionByName(@PathVariable("name") String name) {
        Intention it = financeService.selectIntentionByName(name);
        return new Result<Intention>(true, StatusCode.OK, "查询成功", it);
    }

    @PostMapping("/intention")
    public Result<Integer> insertIntention(@RequestBody Intention intention) {
        int rows = financeService.insertIntentionByName(intention);
        return new Result<Integer>(true, StatusCode.OK, "添加成功", rows);
    }

    @PutMapping("/intention")
    public Result<Integer> updateIntention(@RequestBody Intention intention) {
        int rows = financeService.updateIntentionByName(intention);
        return new Result<Integer>(true, StatusCode.OK, "修改成功", rows);
    }

    @GetMapping("/recommend/none/{name}")
    public Result<List<Recommend>> selectWithNoneIntention(@PathVariable("name") String name) {
        List<Recommend> list = financeService.selectWithNoneIntention(name);
        return new Result<List<Recommend>>(true, StatusCode.OK, "查询成功", list);
    }

    @GetMapping("/recommend/all/{name}")
    public Result<List<Recommend>> selectAllRecommend(@PathVariable("name") String name) {
        List<Recommend> list = financeService.selectAllRecommend(name);
        return new Result<List<Recommend>>(true, StatusCode.OK, "查询成功", list);
    }

    // 查询推荐融资人（根据是否存在意向自动分流）
    @GetMapping("/selectRecommendByName")
    public Result<List<Recommend>> selectRecommendByName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication != null ? authentication.getName() : null;
        Intention it = financeService.selectIntentionByName(name);
        List<Recommend> list = (it == null || it.getItem() == null || it.getItem().isEmpty())
                ? financeService.selectWithNoneIntention(name)
                : financeService.selectAllRecommend(name);
        return new Result<List<Recommend>>(true, StatusCode.OK, "查询成功", list);
    }

    // 查询个人融资（按当前登录用户名 ownName）
    @GetMapping("/selectByName")
    public Result<List<Finance>> selectByName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication != null ? authentication.getName() : null;
        List<Finance> list = financeService.selectByName(name);
        return new Result<List<Finance>>(true, StatusCode.OK, "查询成功", list);
    }

    // 根据ID查询融资
    @GetMapping("/selectById/{id}")
    public Result<Finance> selectById(@PathVariable("id") Integer id) {
        Finance finance = financeService.queryById(id);
        return new Result<Finance>(true, StatusCode.OK, "查询成功", finance);
    }

    // 根据ID删除融资
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteByIdPath(@PathVariable("id") Integer id) {
        boolean ok = financeService.deleteById(id);
        return new Result<Boolean>(true, StatusCode.OK, ok ? "删除成功" : "删除失败", ok);
    }

}

